#ifndef UTILS_H
#define UTILS_H
#include <QByteArray>
#include <QString>
#include <QFile>
#include <QStandardPaths>
#include <QFile>

const char *get_env_var(const char *var, int envc, const char *envs)
{
    if (envc > 0) {
        // get the var from envs
        const char *env_l = envs;
        int ln = strlen(var);
        for (int i = 0;  i < envc; i++) {
            if (strncmp(env_l, var, ln) == 0) {
                return env_l + ln;
            }
            while (*env_l != 0) {
                env_l++;
            }
            env_l++;
        }
    }
    return nullptr;
}

QByteArray execpath_avoid_loops(const QString exec, QStringList paths, bool avoid_loops)
{
//    const QRegExp pathSepRegExp(QStringLiteral("[:\b]"));
//    if (envc > 0) { // use the passed environment
//        const char *path = get_env_var("PATH=", envc, envs);
//        if (path != nullptr) {
//            paths = QFile::decodeName(path).split(pathSepRegExp);
//        }
//    } else {
//        paths = QString::fromLocal8Bit(qgetenv("PATH")).split(pathSepRegExp, Qt::KeepEmptyParts);
//        paths.prepend(QFile::decodeName(KDE_INSTALL_FULL_LIBEXECDIR_KF5));
//    }
    QString execpath;
    if(paths.size() != 0)
    {
        execpath = QStandardPaths::findExecutable(exec, paths);
    }
    else
    {
        execpath = QStandardPaths::findExecutable(exec);
    }
    if (avoid_loops && !execpath.isEmpty()) {
        const int pos = execpath.lastIndexOf(QLatin1Char('/'));
        const QString bin_path = execpath.left(pos);
        for (QStringList::Iterator it = paths.begin();
                it != paths.end();
                ++it) {
            if (*it == bin_path || *it == bin_path + QLatin1Char('/')) {
                paths.erase(it);
                break; // -->
            }
        }
        execpath = QStandardPaths::findExecutable(exec, paths);
    }
    return QFile::encodeName(execpath);
}
#endif // UTILS_H
